from django.http import Http404
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView, ListAPIView,RetrieveAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaSerializer, SubAreaSerializer


# list
# retrieve
#该接口的优化:
class AreasViewSet(CacheResponseMixin,ReadOnlyModelViewSet):
    """地区视图集"""
    # 关闭分页
    pagination_class = None

    def get_serializer_class(self):
        if self.action=='list':
            return AreaSerializer
        else:
            return SubAreaSerializer
    def get_queryset(self):
        if self.action=='list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()






# #获取所有省级地区的信息
# # class AreasView(GenericAPIView):  #最初的代码
# class AreasView(ListAPIView):     #第一次优化的代码
#     serializer_class = AreaSerializer
#     queryset = Area.objects.filter(parent=None)


    # def get(self,request):      #最初的代码
    #     """
    #     获取所有省级地区的信息
    #     1.查询获取所有的省级地区的信息
    #     2.将省级地区的信息序列化并返回
    #     """
    #     #1.查询获取所有的省级地区的信息
    #     areas=Area.objects.filter(parent=None)
    #
    #     # 2.将省级地区的信息序列化并返回
    #     serializer=self.get_serializer(areas,many=True)
    #     return Response(serializer.data)  #最初的代码


#GET /areas/(?P<pk>\d+)/
# # class SubAreasView(GenericAPIView):   #最初代码
# class SubAreasView(RetrieveAPIView):   #第二次优化的代码:RetrieveAPIView
#     serializer_class = SubAreaSerializer
#     queryset = Area.objects.all()

    # get_object() :从查询集获取指定的对象,默认根据pk进行查询

    # def get(self,request,pk):    #最初代码
    #     """
    #     获取指定地区的信息
    #     1.根据pk获取指定地区的信息
    #     2.将指定地区的信息序列化并返回(下级进行嵌套序列化)
    #     """
    #     #1.根据pk获取指定地区的信息
    #     try:
    #         area=Area.objects.get(pk=pk)
    #     except Area.DoesNotExist:
    #         raise Http404
    #     #2.将指定地区的信息序列化并返回(下级地区进行嵌套序列化)
    #     serializer=self.get_serializer(area)
    #     return Response(serializer.data)    #最初代码


